package com.tanhua.dubbo.api;

import com.tanhua.dubbo.api.mongo.FriendApi;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * 好友服务接口实现类
 */
@DubboService
@Slf4j
public class FriendApiImpl implements FriendApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 添加好友（双向关系-2条记录）
     *
     * @param friendId
     * @param userId
     */
    @Override
    public void add(Long friendId, Long userId) {
        addFriend(friendId,userId);
        addFriend(userId,friendId);
        log.debug("************添加好友成功了****friendId{}*******userId{}***",friendId,userId);
    }

    /**
     * 联系人列表分页列表
     *
     * @param page
     * @param pageSize
     * @param userId
     */
    @Override
    public PageResult<Friend> findPageFriend(Long page, Long pageSize, Long userId) {
        long start = (page-1)*pageSize;//从那条开始查询 （page-1）*pageSize
        //1.查询总记录数
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        long count = mongoTemplate.count(query, Friend.class);
        //2.每页展示的数据
        query.skip(start).limit(pageSize.intValue());
        //2.1根据friendId排序
        query.with(Sort.by(Sort.Direction.ASC,"friendId"));
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        return new PageResult<>(page,pageSize,count,friendList);
    }

    /**
     * 添加好友
     * @param friendId
     * @param userId
     */
    private void addFriend(Long friendId, Long userId) {
        //1.查询好友关系是否存在
        Query query = new Query();
        query.addCriteria(Criteria.where("friendId").is(friendId).and("userId").is(userId));
        if(!mongoTemplate.exists(query,Friend.class)) {
            //2.添加好友关系
            Friend friend = new Friend();
            friend.setUserId(userId);//当前用户id
            friend.setFriendId(friendId);//好友id
            friend.setCreated(System.currentTimeMillis());//添加好友时间
            mongoTemplate.insert(friend);
        }
    }
}
